<script lang="ts" setup>
import type { CommentApi } from '#/api/wedding/comment';

import { ref } from 'vue';

import { Avatar, Button, Image, message, Rate } from 'ant-design-vue';
import { IconifyIcon } from '@vben/icons';

import { replyComment, toggleLike } from '#/api/wedding/comment';

const props = defineProps<{
  comment: CommentApi.Comment;
  showReplies?: boolean;
  showTargetLink?: boolean; // 是否显示跳转到目标的链接
}>();

const emit = defineEmits<{
  like: [comment: CommentApi.Comment];
  reply: [];
}>();

const showReplyBox = ref(false);
const replyContent = ref('');
const replying = ref(false);

// 格式化时间
function formatTime(time: number | string) {
  // 处理时间戳（毫秒）或日期字符串
  const date = typeof time === 'number' ? new Date(time) : new Date(time);
  const now = new Date();
  const diff = now.getTime() - date.getTime();

  const minutes = Math.floor(diff / (1000 * 60));
  const hours = Math.floor(diff / (1000 * 60 * 60));
  const days = Math.floor(diff / (1000 * 60 * 60 * 24));

  if (minutes < 1) {
    return '刚刚';
  } else if (minutes < 60) {
    return `${minutes}分钟前`;
  } else if (hours < 24) {
    return `${hours}小时前`;
  } else if (days < 7) {
    return `${days}天前`;
  } else {
    return date.toLocaleDateString();
  }
}

// 跳转到评论目标页面
function goToTarget() {
  const { targetType, targetId } = props.comment;

  let path = '';
  switch (targetType) {
    case 'dress': {
      path = `/wedding/dress-preview/${targetId}`;
      break;
    }
    case 'photographer': {
      path = `/wedding/photographer/detail/${targetId}`;
      break;
    }
    case 'makeupartist': {
      path = `/wedding/makeupartist/detail/${targetId}`;
      break;
    }
    case 'package': {
      path = `/wedding/package/detail/${targetId}`;
      break;
    }
    default: {
      message.warning('未知的目标类型');
      return;
    }
  }

  // 在新标签页打开
  window.open(path, '_blank');
}

// 格式化目标类型显示
function formatTargetType(type: string) {
  const typeMap: Record<string, string> = {
    dress: '婚纱',
    photographer: '摄影师',
    makeupartist: '化妆师',
    package: '套餐',
  };
  return typeMap[type] || type;
}

// 点赞/取消点赞
async function handleLike() {
  try {
    await toggleLike(props.comment.id);
    emit('like', props.comment);
  } catch (error) {
    message.error('操作失败');
  }
}

// 回复评论
async function handleReply() {
  if (!replyContent.value.trim()) {
    message.warning('请输入回复内容');
    return;
  }

  try {
    replying.value = true;
    await replyComment({
      parentId: props.comment.id,
      content: replyContent.value.trim(),
    });

    message.success('回复成功');
    replyContent.value = '';
    showReplyBox.value = false;
    emit('reply');
  } catch (error) {
    message.error('回复失败');
  } finally {
    replying.value = false;
  }
}

// 取消回复
function handleCancelReply() {
  replyContent.value = '';
  showReplyBox.value = false;
}
</script>

<template>
  <div class="comment-item border-b border-gray-100 pb-4">
    <!-- 评论头部 -->
    <div class="mb-3 flex items-start gap-3">
      <Avatar :src="comment.userAvatar" :size="40" class="flex-shrink-0">
        {{ comment.userName?.charAt(0) }}
      </Avatar>

      <div class="min-w-0 flex-1">
        <div class="mb-1 flex items-center gap-2">
          <span class="font-medium text-gray-900">{{ comment.userName }}</span>
          <Rate
            :value="comment.rating"
            disabled
            size="small"
            class="text-yellow-500"
          />
          <span class="text-sm text-gray-500">{{
            formatTime(comment.createTime)
          }}</span>
        </div>

        <!-- 回复目标 -->
        <div v-if="comment.replyToUser" class="mb-1 text-sm text-blue-600">
          回复 @{{ comment.replyToUser }}
        </div>
      </div>
    </div>

    <!-- 评论内容 -->
    <div class="mb-3 ml-11">
      <p class="whitespace-pre-wrap leading-relaxed text-gray-800">
        {{ comment.content }}
      </p>

      <!-- 评论图片 -->
      <div v-if="comment.images && comment.images.length > 0" class="mt-3">
        <Image.PreviewGroup>
          <Image
            v-for="(img, index) in comment.images"
            :key="index"
            :src="img"
            :width="80"
            :height="80"
            class="mb-2 mr-2 rounded object-cover"
          />
        </Image.PreviewGroup>
      </div>
    </div>

    <!-- 评论操作 -->
    <div class="ml-11 flex items-center gap-4">
      <Button
        type="text"
        size="small"
        :class="{ 'text-red-500': comment.isLiked }"
        @click="handleLike"
      >
        <template #icon>
          <IconifyIcon
            :icon="comment.isLiked ? 'lucide:heart' : 'lucide:heart'"
            :class="{ 'fill-current': comment.isLiked }"
          />
        </template>
        {{ comment.likeCount || 0 }}
      </Button>

      <Button type="text" size="small" @click="showReplyBox = !showReplyBox">
        <template #icon>
          <IconifyIcon icon="lucide:message-circle" />
        </template>
        回复
      </Button>

      <!-- 跳转到目标页面（仅在管理后台显示） -->
      <Button
        v-if="showTargetLink"
        type="text"
        size="small"
        class="text-blue-600 hover:text-blue-800"
        @click="goToTarget"
        title="查看评论目标"
      >
        <template #icon>
          <IconifyIcon icon="lucide:external-link" />
        </template>
        查看{{ formatTargetType(comment.targetType) }}
      </Button>
    </div>

    <!-- 回复列表 -->
    <div
      v-if="showReplies && comment.replies && comment.replies.length > 0"
      class="ml-11 mt-3 space-y-3"
    >
      <div
        v-for="reply in comment.replies"
        :key="reply.id"
        class="rounded bg-gray-50 p-3"
      >
        <div class="mb-2 flex items-center gap-2">
          <Avatar :src="reply.userAvatar" :size="24">
            {{ reply.userName?.charAt(0) }}
          </Avatar>
          <span class="text-sm font-medium text-gray-900">{{
            reply.userName
          }}</span>
          <span v-if="reply.replyToUser" class="text-xs text-blue-600">
            回复 @{{ reply.replyToUser }}
          </span>
          <span class="text-xs text-gray-500">{{
            formatTime(reply.createTime)
          }}</span>
        </div>
        <p class="whitespace-pre-wrap text-sm text-gray-700">
          {{ reply.content }}
        </p>
        <div class="mt-2 flex items-center gap-3">
          <Button
            type="text"
            size="small"
            :class="{ 'text-red-500': reply.isLiked }"
            @click="handleLike"
          >
            <template #icon>
              <IconifyIcon
                icon="lucide:heart"
                :class="{ 'fill-current': reply.isLiked }"
              />
            </template>
            {{ reply.likeCount || 0 }}
          </Button>
        </div>
      </div>
    </div>

    <!-- 回复框 -->
    <div v-if="showReplyBox" class="ml-11 mt-3 rounded bg-gray-50 p-3">
      <div class="mb-2">
        <textarea
          v-model="replyContent"
          placeholder="写下你的回复..."
          class="w-full resize-none rounded border p-2"
          rows="3"
          maxlength="200"
        ></textarea>
      </div>
      <div class="flex justify-end gap-2">
        <Button size="small" @click="handleCancelReply"> 取消 </Button>
        <Button
          type="primary"
          size="small"
          :loading="replying"
          :disabled="!replyContent.trim()"
          @click="handleReply"
        >
          回复
        </Button>
      </div>
    </div>
  </div>
</template>

<style scoped>
.comment-item {
  @apply w-full;
}

.comment-item:last-child {
  @apply border-b-0;
}
</style>
